﻿using System;
using System.Web;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebControls;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Net.Mime;
using System.Net;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

namespace OARepository.Layouts.OARepository
{
    public partial class Item : UnsecuredLayoutsPageBase
    {
        private RepoContext repoContext = null;

        protected void Page_Load(object sender, EventArgs e)
        {
            string path = HttpContext.Current.Request.PathInfo;

            List<String> parts = new List<string>(path.Split('/'));
            parts.RemoveAt(0); // PathInfo starts with '/'

            if (parts.Count != 2)
                throw new HttpException((int)HttpStatusCode.NotFound, "Not Found");

            RepoContext = new RepoContext(parts[0], parts[1]);

            Title = RepoContext.Item.Title;
            PlaceHolderPageTitle.Text = SPEncode.HtmlEncode(Title);
            {
                HtmlAnchor link = new HtmlAnchor();
                link.HRef = RepoContext.ListUrl();
                link.InnerText = SPEncode.HtmlEncode(RepoContext.List.Title);

                PlaceHolderPageTitleInTitleArea.Controls.Add(link);

                Literal crumb = new Literal();
                crumb.Text = ": " + SPEncode.HtmlEncode(Title);

                PlaceHolderPageTitleInTitleArea.Controls.Add(crumb);
            }
            ContentTitle.InnerText = Title;

            NameValueCollection dc = RepoContext.DublinCore();
            foreach (string key in dc.AllKeys)
            {
                foreach (string value in dc.GetValues(key))
                {
                    HtmlMeta meta = new HtmlMeta();
                    meta.Name = "DC." + key;
                    meta.Content = value;
                    Page.Header.Controls.Add(meta);
                }
            }

            Content.Controls.Add(this.RenderFulltext(RepoContext.Item));

            Content.Controls.Add(this.RenderMetadataTable(RepoContext.Item));

            Table tab = new Table();
            tab.Attributes.Add("id", "item_metadata");
            tab.Style.Add("display", "none");
            tab.BorderStyle = BorderStyle.Solid;
            tab.BorderWidth = 1;
            Content.Controls.Add(tab);

            foreach (SPField field in RepoContext.Item.Fields)
            {
                TableRow row = new TableRow();

                TableCell td1 = new TableCell();
                td1.Text = field.Title + " (" + field.TypeAsString + ")";

                TableCell td2 = new TableCell();
                td2.Text = field.Id.ToString();

                TableCell td3 = new TableCell();
                td3.Style.Add("max-width", "20em");
                td3.Style.Add("overflow", "hidden");
                try
                {
                    td3.Text = RepoContext.Item[field.Id].ToString();
                }
                catch (NullReferenceException)
                {
                    td3.Style.Add("font-style", "italic");
                    td3.Text = "UNSPECIFIED";
                }
                catch (Exception err)
                {
                    td3.Style.Add("font-weight", "bold");
                    td3.Text = err.ToString();
                }

                row.Cells.AddRange(new TableCell[] { td1, td2, td3 });
                foreach (TableCell td in row.Cells)
                {
                    td.BorderStyle = BorderStyle.Solid;
                    td.BorderWidth = 1;
                }
                tab.Controls.Add(row);
            }
        }

        protected override bool AllowAnonymousAccess
        {
            get
            {
                return true;
            }
        }

        protected RepoContext RepoContext
        {
            get
            {
                return repoContext;
            }
            set
            {
                repoContext = value;
            }
        }

        protected Table RenderMetadataTable(SPItem item)
        {
            Table table = new Table();

            NameValueCollection data = RepoContext.Metadata();
            foreach (string key in data.AllKeys)
            {
                foreach (string value in data.GetValues(key))
                {
                    TableRow row = new TableRow();

                    TableCell th = new TableCell();
                    th.Text = SPEncode.HtmlEncode(key + ":");
                    row.Controls.Add(th);

                    TableCell td = new TableCell();
                    td.Text = SPEncode.HtmlEncode(value);
                    row.Controls.Add(td);

                    table.Controls.Add(row);
                }
            }

            return table;
        }

        protected BulletedList RenderFulltext(SPListItem item)
        {
            BulletedList list = new BulletedList();
            list.DisplayMode = BulletedListDisplayMode.HyperLink;
            try
            {
                SPAttachmentCollection attachments = item.Attachments;
                lock (this)
                {
                    for (int i = 0; i < attachments.Count; ++i)
                    {
                        attachments.GetEnumerator();
                        SPFile file = SPContext.Current.Web.GetFile(attachments.UrlPrefix + attachments[i]);
                        ListItem li = new ListItem(
                                file.Name + " (" + SPUtility.FormatSize(file.Length) + ")",
                                attachments.UrlPrefix + attachments[i]
                            );
                        list.Items.Add(li);
                    }
                }
            }
            catch (ArgumentOutOfRangeException)
            {
                // is a Document Library item
            }
            return list;
        }
    }
}
